﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Avatar.Model;
using AvatarHelper;
using System.Data.Linq;

namespace Avatar.ADService
{
    public static class ADManager
    {
        public static bool BuyAD(
            string _title,
            Guid _id,
            string _user,
            Guid _adCategory,
            string _iconURL)
        {
            #region

            if (string.IsNullOrEmpty(_user)) throw new Exception("企业用户不能为空");
            if (string.IsNullOrEmpty(_iconURL)) _iconURL = "./ad/jobad/normal.gif";

            #endregion

            return DBHelper.Save<AD>(new AD(),
                j => j.ID == _id,
                ad => ad.AdsBy == _user && ad.ADCategoryID == _adCategory,
                delegate(AD _ad)
                {
                    _ad.ID = Guid.NewGuid();
                    _ad.Content = _iconURL;
                    _ad.AdsBy = _user;
                    _ad.ADCategoryID = _adCategory;
                    _ad.Title = _title;
                },
                delegate(AD _ad)
                {
                    _ad.Title = _title;
                    _ad.Content = _iconURL;
                }, "编辑招聘广告出错:");
        }
        public static Guid CreateAD(
            string _title,
            string _user,
            Guid _adCategory,
            string _content)
        {
            #region 入口检测

            if (string.IsNullOrEmpty(_user)) throw new Exception("企业用户不能为空");
            //if (string.IsNullOrEmpty(_content)) _content = "./ad/jobad/normal.gif";
            if (string.IsNullOrEmpty(_content)) throw new Exception("广告内容不能为空");

            #endregion

            var _id = Guid.NewGuid();

            var _ad = new AD();
            _ad.ID = _id;
            _ad.Content = _content;
            _ad.AdsBy = _user;
            _ad.ADCategoryID = _adCategory;
            _ad.Title = _title;

            using (var _adc = DBHelper.GetDataContext())
            {
                if (_adc.AD.Where(a => a.AdsBy == _ad.AdsBy && a.ADCategoryID == _ad.ADCategoryID && a.Content == _ad.Content).FirstOrDefault() == null)
                {
                    _adc.AD.InsertOnSubmit(_ad);

                    _adc.SubmitChanges();
                }
                else
                {
                    throw new Exception("创建广告出错:已存在相同内容的广告.");
                }
            }

            return _id;
        }
        /// <summary>
        /// 根据广告发布者获取广告列表
        /// </summary>
        /// <param name="_user">广告发布者帐号</param>
        /// <returns></returns>
        public static List<AD> GetAD(string _user)
        {
            return DBHelper.GetAll<AD>(ad => ad.AdsBy == _user, "获取招聘广告列表出错:");
        }
        public static AD GetAD(Guid _id)
        {
            return DBHelper.Get<AD>(ad => ad.ID == _id, "获取招聘广告列表出错:");
        }
        /// <summary>
        /// 根据广告分类获取广告列表
        /// </summary>
        /// <param name="_type"></param>
        /// <returns></returns>
        public static List<AD> GetJobADList(string _categoryName)
        {
            if (string.IsNullOrEmpty(_categoryName)) throw new Exception("此广告位未设置广告分类,将不会显示任何广告内容。");

            using (var _adc = DBHelper.GetDataContext())
            {
                var _category = _adc.ADCategory.FirstOrDefault(c => c.CategoryName == _categoryName);
                if (_category == null) throw new Exception("广告分类不存在，请在系统后台加入相关广告分类设置，或设置显示其他类型广告。");

                #region 关闭过期广告
                var _adClose = _adc.AD.Where(a => a.ADCategoryID == _category.ID && a.Open == true && a.OverDatetime < DateTime.Now);
                foreach (var _a in _adClose)
                {
                    _a.Open = false;
                }
                _adc.SubmitChanges();
                #endregion

                var _max = _category.MaxColumn * _category.MaxRow;
                
                var _adList = _adc.AD.Where(a => a.ADCategoryID == _category.ID && a.Open == true && a.OverDatetime >= DateTime.Now).OrderByDescending(a => a.StartDatetime).Take(_max).ToList();
                List<AD> _jobADList = new List<AD>();
                for (int _i = 0; _i < _max; _i++)
                {
                    if (_i < _adList.Count)
                    {
                        _jobADList.Add(_adList[_i]);
                    }
                    else
                    {
                        var _ad = new AD();
                        _ad.Content = string.Empty;

                        _jobADList.Add(new AD());
                    }
                }

                return _jobADList;
            }
        }

        public static void ADPublish(
            string _title,
            Guid _adCategoryID,
            string _adsBy,
            string _adImageURL,
            int _periodID)
        {
            try
            {
                using (var _adc = DBHelper.GetDataContext())
                {
                    AD _ad = new AD();

                    _ad.ID = Guid.NewGuid();
                    _ad.Title = _title;
                    _ad.Open = false;
                    _ad.ADCategoryID = _adCategoryID;
                    _ad.AdsBy = _adsBy;
                    _ad.Content = _adImageURL;
                    _ad.PeriodID = _periodID;

                    _adc.AD.InsertOnSubmit(_ad);
                    _adc.SubmitChanges();

                    var _balance = _adc.CompanyFinancialAccount.Where(a => a.Company == _adsBy).FirstOrDefault();
                    if (_balance == null) throw new Exception("帐户余额不足，请充值后进入“广告管理”中为广告付费。付费后广告才会正常显示在相应位置。");

                    var _adPrice = _adc.ADPrice.Where(p => p.ADCategoryID == _adCategoryID && p.PeriodID == _periodID).FirstOrDefault();
                    if (_adPrice == null) throw new Exception("未找到与此广告位对应时长的广告资费，广告投放失败，请与客服人员联系。");

                    if (_balance.Balance < _adPrice.Price) throw new Exception("帐户余额不足，请充值后进入“广告管理”中为广告付费。付费后广告才会正常显示在相应位置。");

                    _balance.Balance -= _adPrice.Price;
                    var _log = new CompanyFinancialAccountLog();
                    _log.AccountCategoryID = 5;
                    _log.Date = DateTime.Now;
                    _log.Money = _adPrice.Price;
                    _log.Company = _ad.AdsBy;
                    _log.Balance = _balance.Balance;
                    _adc.CompanyFinancialAccountLog.InsertOnSubmit(_log);

                    _ad.Open = true;
                    _ad.StartDatetime = DateTime.Now;
                    _ad.OverDatetime = DateTime.Now.AddMonths(_adPrice.Period.Month);

                    _adc.SubmitChanges();
                }
            }
            catch (Exception _e)
            {
                throw new Exception("广告发布出错：" + _e.Message);
            }
        }
        public static void ADPublishAdmin(
            string _title,
            Guid _adCategoryID,
            string _adsBy,
            string _adImageURL,
            string _url,
            int _periodID)
        {
            try
            {
                using (var _adc = DBHelper.GetDataContext())
                {
                    AD _ad = new AD();

                    _ad.ID = Guid.NewGuid();
                    _ad.Title = _title;
                    _ad.ADCategoryID = _adCategoryID;
                    _ad.AdsBy = _adsBy;
                    _ad.Content = _adImageURL;
                    _ad.PeriodID = _periodID;
                    _ad.Open = false;
                    if (!string.IsNullOrEmpty(_url)) _ad.URL = _url;

                    _adc.AD.InsertOnSubmit(_ad);

                    _ad.Open = true;
                    _ad.StartDatetime = DateTime.Now;
                    var _adPrice = _adc.ADPrice.Where(p => p.PeriodID == _ad.PeriodID && p.ADCategoryID == _ad.ADCategoryID).FirstOrDefault();
                    _ad.OverDatetime = DateTime.Now.AddMonths(_adPrice.Period.Month);

                    _adc.SubmitChanges();
                }
            }
            catch (Exception _e)
            {
                throw new Exception("广告发布出错：" + _e.Message);
            }
        }
    }
}
